package com.qf.smartplatform.events.listeners;

import com.qf.smartplatform.events.UserLoginEvent;
import com.qf.smartplatform.mapper.UserOnlineMapper;
import com.qf.smartplatform.pojo.Logininfor;
import com.qf.smartplatform.pojo.User;
import com.qf.smartplatform.pojo.UserOnline;
import com.qf.smartplatform.service.UserService;
import com.qf.smartplatform.utils.RequestUtil;
import com.qf.smartplatform.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.security.Security;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;

/**
 * projectName:day12_27_Test
 * author:guoLei
 * time:2022/1/4 11:23
 * description:
 */
@Component
public class UserLoginListener {

    private UserService userService;

    private UserOnlineMapper userOnlineMapper;

    @Autowired
    public void setUserOnlineMapper(UserOnlineMapper userOnlineMapper) {
        this.userOnlineMapper = userOnlineMapper;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    @EventListener

    public void upDateUserInfo(UserLoginEvent loginEvent) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        User user = SecurityUtils.getUser();

        CompletableFuture.runAsync(() -> {
            try {
                String ip = RequestUtil.getRemoteHost(request);
                user.setCurrentLogin(new Date());
                user.setCurrentLoginIp(ip);
                userService.updateUserLogin(user);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    @EventListener
    public void upDateUserOnline(UserLoginEvent loginEvent) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        User user = SecurityUtils.getUser();

        CompletableFuture.runAsync(() -> {
            try {
                Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);
                String ip = RequestUtil.getRemoteHost(request);
                UserOnline userOnline = new UserOnline();
                userOnline.setSessionId(request.getSession().getId());
                userOnline.setLoginName(user.getUsername());
                userOnline.setStartTimestamp(new Date());
                userOnline.setStatus("1");
                userOnline.setIpaddr(ip);
                userOnline.setLoginLocation(RequestUtil.getLocationByIp(ip));
                userOnline.setOs(osAndBrowserInfo.get("os"));
                userOnline.setBrowser(osAndBrowserInfo.get("browser"));
                userOnline.setExpireTime(30L);
                UserOnline currentLogin = userOnlineMapper.selectByLoginName(user.getUsername());
                if (currentLogin != null) {

                    userOnlineMapper.deleteByLoginName(user.getUsername());
                }
                userOnlineMapper.addOnlineData(userOnline);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    }

//    @EventListener

//@Autowired
//    public void setLogininfor(Logininfor logininfor) {
//        this.logininfor = logininfor;
//    }
//
//    public void onLoginLog(UserLoginEvent loginEvent) {
//        HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        User user = SecurityUtils.getUser();
//        CompletableFuture.runAsync(() -> {
//            try {
//                Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(servletRequest);
//                //获取用户使用设备的ip地址
//                String remoteHost = RequestUtil.getRemoteHost(servletRequest);
//                UserOnline userOnline = new UserOnline();
//                userOnline.setSessionId(servletRequest.getSession().getId());
//                userOnline.setLoginName(user.getUsername());
//                userOnline.setStartTimestamp(new Date());
//                //将用户的设备状态设置为在线状态
//                userOnline.setStatus("1");
//                userOnline.setIpaddr(remoteHost);
//                userOnline.setLoginLocation(RequestUtil.getLocationByIp(remoteHost));//请求第三方服务器,需要时间,所以应该放到单独的线程中执行
//                userOnline.setOs(osAndBrowserInfo.get("os"));
//                userOnline.setBrowser(osAndBrowserInfo.get("browser"));
//                userOnline.setExpireTime(30L);
//                //获取用户名
//                UserOnline currentLogin = userOnlineMapper.selectByLoginName(user.getUsername());
//                //查询数据库中用户登录的设备信息，若该用户信息已存在，则应先将其删除，之后重新添加，若该用户信息不存在，可直接添加
//                if (currentLogin.getStatus().equalsIgnoreCase("1")) {
//
//                    userOnlineMapper.deleteByLoginName(user.getUsername());
//                }
//                userOnlineMapper.addOnlineData(userOnline);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        });
//    }
}
